﻿// -----------------------------------------------------------------------
// <copyright file="RedirectHandler.cs" company="Microsoft">
// Handler for redirect server mode
// </copyright>
// -----------------------------------------------------------------------

using WebServer.BusinessLogic.Communication;

namespace WebServer.BusinessLogic.Handlers
{
    using System;
    using System.IO;
using WebServer.BusinessLogic.Handlers.Interface;

    /// <summary>
    /// Class for process redirect mode
    /// </summary>
    public class RedirectHandler : Handler
    {
        private Configurator _configurator;
        private IFileSystemProvider _fileSystemProvider;

        /// <summary>
        /// Default constructor
        /// </summary>
        public RedirectHandler()
        {
            _configurator = Configurator.Instance;
            _fileSystemProvider = new FileSystemProvider();
        }

        /// <summary>
        /// Constructor for injection
        /// </summary>
        /// <param name="configurator">Configurator to inject</param>
        /// <param name="provider">FileSystem injection</param>
        public RedirectHandler(Configurator configurator, IFileSystemProvider provider) : this()
        {
            _configurator = configurator;
            _fileSystemProvider = provider;
        }

        /// <summary>
        /// Redirecting to another server if content isn't found
        /// </summary>
        /// <param name="request">http request</param>
        /// <returns>http response object</returns>
        public override Response Handle(Request request)
        {
            string filePath = request.HttpPath;

            // checking existing file on local drive
            if (!_fileSystemProvider.FileExists(filePath) && _configurator.ServerMode == ServerConfiguration.Redirect)
            {              
                foreach (string remoteserver in _configurator.RemoteServers)
                {
                    string urlToFile = remoteserver.TrimEnd(new[] { '/' }) + "/" + filePath.TrimStart(new[] { '/' });

                    urlToFile = !urlToFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "http://" + urlToFile : urlToFile;

                    Response remoteResponse = Communicator.GetPage(urlToFile);
                    if (remoteResponse.HttpResponseCode == 200)
                    {
                        var r = new Response();
                        r.SetRedirect(urlToFile, request);
                        return r;
                    }
                }
            }

            return this.NextHandler.Handle(request);
        }
    }
}
